package com.jsb.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.jsb.service.CmsCategoryService;
import com.jsb.service.ExtraCategoryService;
import com.jsb.common.config.Global;
import com.jsb.common.utils.IdGen;
import com.jsb.common.utils.StringUtils;
import com.jsb.dto.CmsCategoryDto;
import com.jsb.dto.TreeCategory;
import com.jsb.model.CmsCategory;
import com.jsb.model.CmsCategoryExample;
import com.jsb.model.CmsCategoryExample.Criteria;

@Controller
public class CmsCategoryController{
	
	private static final Logger log = Logger.getLogger(CmsCategoryController.class);
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/cmsCategory/list.do";
	
	@Resource
	private CmsCategoryService cmsCategoryService;
	
	@Resource
	private ExtraCategoryService extraCategoryService;
	
	@RequestMapping("/cmsCategory/list")
	public String list(
			Model model,String pid,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		getCategories(model, pid, pageNum, pageSize);
		return "/CmsCategory/treelist";
	}
	private void getCategories(Model model, String pid, Integer pageNum,
			Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		if(StringUtils.isEmpty(pid)){
			pid = "1";
		}
		CmsCategoryExample cmsCategoryExample = new CmsCategoryExample();
		Criteria createCriteria = cmsCategoryExample.createCriteria();
		createCriteria.andParentIdEqualTo(pid);
		int totalCount = cmsCategoryService.countCmsCategory(cmsCategoryExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		cmsCategoryExample.setPageIndex((pageNum - 1) * pageSize);
		cmsCategoryExample.setPageSize(pageSize);
		List<CmsCategoryDto> cmsCategorys = cmsCategoryService.getPageCmsCategory(cmsCategoryExample);
		for (CmsCategoryDto cmsCategory : cmsCategorys) {
			CmsCategoryDto parent = (CmsCategoryDto) cmsCategoryService.getCmsCategoryById(cmsCategory.getParentId());
			cmsCategory.setParent(parent);
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("cmsCategorys", cmsCategorys);
	}
//	@RequestMapping("/cmsCategory/list")
	public String list(Model model){
		return "/CmsCategory/list";
	}
	
	@RequestMapping("/cmsCategory/treeTable")
	public String treeTable(Model model,String pid,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize){
		getCategories(model, pid, pageNum, pageSize);
		return "/CmsCategory/treeTable";
	}
	
	@RequestMapping("/cmsCategory/asyncList")
	public String asyncList(Model model,@RequestParam(value = "id", required = false) String id){
		if(StringUtils.isEmpty(id)){
			id = "1";
		}
		List<TreeCategory> treeCategorys = extraCategoryService.findList(id);
		for (TreeCategory treeCategory : treeCategorys) {
			int count = extraCategoryService.count(treeCategory.getId());
			if(count > 0){
				treeCategory.setIsParent(true);
			}
		}
//		if(null == treeCategorys || treeCategorys.size()==0){
//			treeCategorys = null;
//		}
		ObjectMapper mapper = new ObjectMapper();
		String json = null;
		try {
			json = mapper.writeValueAsString(treeCategorys);
			System.out.println(json);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		model.addAttribute("json", json.trim());
		log.info(json);
		return "/json";
	}
	
	@RequestMapping("/cmsCategory/toAdd")
	public String toAdd(Model model, @ModelAttribute("cmsCategory") CmsCategory category) {
		CmsCategory cmsCategory = null;
		if(null != category && null != category.getId()){
			cmsCategory = cmsCategoryService.getCmsCategoryById(category.getId());
		}
		model.addAttribute("cmsCategory",cmsCategory);
		return "/CmsCategory/add";
	}

	@RequestMapping("/cmsCategory/add")
	public String add(Model model, @ModelAttribute("cmsCategory") CmsCategory cmsCategory) {
		cmsCategory.setId(IdGen.uuid());
		cmsCategory.setDelFlag(Global.SHOW);
		cmsCategory.setCreateDate(new Date());
		cmsCategoryService.addCmsCategory(cmsCategory);
		return redirect;
	}

	@RequestMapping("/cmsCategory/del")
	public String del(Model model,
			@RequestParam(value = "id", required = true) String id) {
		int count = extraCategoryService.count(id);
		if(count>0){
			model.addAttribute("json", "{\"status\":\"false\",\"info\":\"该节点下有子节点,请选择叶子节点进行删除！\"}");
			return "/json";
		}
		cmsCategoryService.delCmsCategoryById(id);
//		return redirect;
		model.addAttribute("json", "{\"status\":\"true\",\"info\":\"\"}");
		return "/json";
	}

	@RequestMapping("/cmsCategory/toEdit")
	public String toEdit(Model model,
			@RequestParam(value = "id", required = true) String id) {
		CmsCategory cmsCategory = cmsCategoryService.getCmsCategoryById(id);
		CmsCategoryDto categoryDto = new CmsCategoryDto();
		try {
			BeanUtils.copyProperties(categoryDto, cmsCategory);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String parentId = cmsCategory.getParentId();
		CmsCategory parent = cmsCategoryService.getCmsCategoryById(parentId);
		categoryDto.setParent(parent);
		model.addAttribute("cmsCategory", categoryDto);
		return "/CmsCategory/edit";
	}

	@RequestMapping("/cmsCategory/edit")
	public String edit(Model model, @ModelAttribute("cmsCategory") CmsCategory cmsCategory) {
		cmsCategoryService.updateCmsCategory(cmsCategory);
		return redirect;
	}

	@RequestMapping("/cmsCategory/view")
	public String view(Model model,
			@RequestParam(value = "id", required = true) String id) {
		CmsCategory cmsCategory = cmsCategoryService.getCmsCategoryById(id);
		model.addAttribute("cmsCategory", cmsCategory);
		return "/CmsCategory/view";
	}
}
